import { Injectable, LoggerService } from '@nestjs/common';

@Injectable()
export class AppLoggerService implements LoggerService {
  private context?: string;

  constructor(context?: string) {
    this.context = context;
  }

  setContext(context: string) {
    this.context = context;
  }

  private formatMessage(level: string, message: any, context?: string): string {
    const timestamp = new Date().toISOString();
    const contextStr = context || this.context || 'App';
    return `[${timestamp}] [${level}] [${contextStr}] ${message}`;
  }

  log(message: any, context?: string) {
    console.log(this.formatMessage('LOG', message, context));
  }

  error(message: any, trace?: string, context?: string) {
    console.error(this.formatMessage('ERROR', message, context));
    if (trace) {
      console.error(`[${new Date().toISOString()}] [ERROR] [${context || this.context || 'App'}] Stack Trace:`, trace);
    }
  }

  warn(message: any, context?: string) {
    console.warn(this.formatMessage('WARN', message, context));
  }

  debug(message: any, context?: string) {
    if (process.env.NODE_ENV === 'development') {
      console.debug(this.formatMessage('DEBUG', message, context));
    }
  }

  verbose(message: any, context?: string) {
    if (process.env.NODE_ENV === 'development') {
      console.log(this.formatMessage('VERBOSE', message, context));
    }
  }

  // 自定义日志方法
  info(message: any, context?: string) {
    console.info(this.formatMessage('INFO', message, context));
  }

  success(message: any, context?: string) {
    console.log(`✅ ${this.formatMessage('SUCCESS', message, context)}`);
  }

  warning(message: any, context?: string) {
    console.warn(`⚠️  ${this.formatMessage('WARNING', message, context)}`);
  }

  // API请求日志
  apiRequest(method: string, url: string, body?: any, user?: any) {
    const userInfo = user ? `[User: ${user.id || user.username}]` : '[Anonymous]';
    console.log(`🌐 ${this.formatMessage('API_REQUEST', `${method} ${url} ${userInfo}`, 'HTTP')}`);
    if (body && Object.keys(body).length > 0) {
      console.log(`📝 ${this.formatMessage('API_BODY', JSON.stringify(body, null, 2), 'HTTP')}`);
    }
  }

  apiResponse(method: string, url: string, statusCode: number, responseTime?: number) {
    const timeInfo = responseTime ? `(${responseTime}ms)` : '';
    const emoji = statusCode >= 200 && statusCode < 300 ? '✅' : statusCode >= 400 ? '❌' : '⚠️';
    console.log(`${emoji} ${this.formatMessage('API_RESPONSE', `${method} ${url} ${statusCode} ${timeInfo}`, 'HTTP')}`);
  }

  // 数据库操作日志
  dbQuery(query: string, params?: any[], duration?: number) {
    const timeInfo = duration ? `(${duration}ms)` : '';
    console.log(`🗄️  ${this.formatMessage('DB_QUERY', `${query} ${timeInfo}`, 'Database')}`);
    if (params && params.length > 0) {
      console.log(`📊 ${this.formatMessage('DB_PARAMS', JSON.stringify(params), 'Database')}`);
    }
  }

  dbError(error: any, query?: string) {
    console.error(`❌ ${this.formatMessage('DB_ERROR', error.message, 'Database')}`);
    if (query) {
      console.error(`🔍 ${this.formatMessage('DB_QUERY', query, 'Database')}`);
    }
    if (error.stack) {
      console.error(`📚 ${this.formatMessage('DB_STACK', error.stack, 'Database')}`);
    }
  }

  // 认证相关日志
  authAttempt(username: string, ip?: string) {
    const ipInfo = ip ? `[IP: ${ip}}]` : '';
    console.log(`🔐 ${this.formatMessage('AUTH_ATTEMPT', `Login attempt for ${username} ${ipInfo}`, 'Auth')}`);
  }

  authSuccess(username: string, userId: number) {
    console.log(`✅ ${this.formatMessage('AUTH_SUCCESS', `User ${username} (ID: ${userId}) logged in successfully`, 'Auth')}`);
  }

  authFailure(username: string, reason: string) {
    console.log(`❌ ${this.formatMessage('AUTH_FAILURE', `Login failed for ${username}: ${reason}`, 'Auth')}`);
  }

  // 业务逻辑日志
  business(operation: string, details: any, context?: string) {
    console.log(`💼 ${this.formatMessage('BUSINESS', `${operation}: ${JSON.stringify(details)}`, context || 'Business')}`);
  }

  // 性能监控日志
  performance(operation: string, duration: number, context?: string) {
    const emoji = duration < 100 ? '⚡' : duration < 500 ? '🚀' : '🐌';
    console.log(`${emoji} ${this.formatMessage('PERFORMANCE', `${operation} took ${duration}ms`, context || 'Performance')}`);
  }
}
